from flask import Blueprint, request, Response

from db_init import db
from flask_login import fresh_login_required,current_user
from model.model import Advertise, House, Order
from tools.tools import item2dict, my_route, old_limit
from sqlalchemy import text, not_, and_
from model.model import *
house = Blueprint('house', __name__)


@house.route('/ad', methods=['GET'])
def ad():
    ads = Advertise.query.filter_by().all()
    return my_route(200, item2dict(ads))


@house.route('/<int:h_id>', methods=['GET'])
def house_info(h_id):
    return my_route(200, item2dict(House.query.get(h_id)))


@house.route('/', methods=['GET'])
def get_houses():
    data = dict(request.args)
    order = data.pop('order')
    # offset, limit = old_limit(data)

    # houses = House.query.filter_by(live=0, **data) \
    #     .order_by(text(order)) \
    #     .offset(offset).limit(limit).all()

    # 瀑布流分页
    limit = data.pop('limit')
    end_id = int(data.pop('end_id'))

    start_t = int(data.pop('start_t'))
    end_t = int(data.pop('end_t'))

    orders = Order.query.filter(Order.end_t > start_t, Order.end_t <= end_t).all()

    sql = House.query.filter(House.live == 0, House.id.__gt__(end_id)) \
        .filter(*[getattr(House, k) == v for k, v in data.items()])

    for ord in orders:
        sql = sql.filter(House.id != ord.house_id)
    houses = sql.order_by(text(order)).limit(limit).all()

    return my_route(200, item2dict(houses))

# 评论
@house.route('/comment/<int:h_id>',methods=['GET'])
def get_houses_comment(h_id):
    comments = Comment.query.filter(Comment.house_id == h_id).all()
    comments = item2dict(comments)

    temp_comments = {v['id']:v for v in comments}
    ret_data={}

    for k,v in temp_comments.items():
        if v.get('beau') not in temp_comments:
            ret_data[v['id']]=v
        else:
            beau = temp_comments.get(v['beau'])
            beau['son'] = beau.get('son',[]+[v])

    return my_route(200,ret_data)

@house.route('/comment/<int:h_id>', methods=['POST'])
def add_houses_comment(h_id):
    data = request.json

    # 评论数加一
    if 'root_id' in data:
        Comment.query.filter_by(id=data['root_id']).update({'num': Comment.num + 1})

    # 加新评论
    db.session.add(Comment(**data))
    db.session.commit()
    return my_route(200)

@house.route('/add_house',methods=['post'])
def add_house():
    data = request.json
    data['mndloaster_id'] = current_user.id
    if current_user.lard:
        db.session.add(House(**data))
        db.session.commit()
        return my_route(200)
    return my_route(401)

